<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理 - 管理员控制台</title>
    <link href="https://cdn.jsdelivr.net/npm/remixicon@3.5.0/fonts/remixicon.css" rel="stylesheet">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
            font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Microsoft YaHei', sans-serif;
            background: #f5f7fa;
            min-height: 100vh;
        }
        .top-nav {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 0 30px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1000;
            height: 60px;
            display: flex;
            align-items: center;
            justify-content: space-between;
        }
        .logo {
            font-size: 24px;
            font-weight: bold;
            display: flex;
            align-items: center;
            gap: 10px;
            text-decoration: none;
            color: white;
        }
        .logout-btn {
            padding: 8px 20px;
            background: rgba(255,255,255,0.2);
            border: 1px solid rgba(255,255,255,0.3);
            color: white;
            border-radius: 20px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 5px;
        }
        .container { margin-top: 80px; padding: 30px; }
        .page-header {
            margin-bottom: 30px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .page-title { font-size: 28px; color: #333; }
        .btn-primary {
            padding: 10px 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            border-radius: 8px;
            cursor: pointer;
            display: inline-flex;
            align-items: center;
            gap: 8px;
        }
        .alert {
            padding: 12px 20px;
            border-radius: 8px;
            margin-bottom: 20px;
        }
        .alert-success { background: #d1fae5; border: 1px solid #10b981; color: #059669; }
        .alert-error { background: #fee2e2; border: 1px solid #ef4444; color: #dc2626; }
        .users-table-container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.05);
            overflow: hidden;
        }
        .table-header { padding: 20px; border-bottom: 1px solid #e0e0e0; }
        table { width: 100%; border-collapse: collapse; }
        thead { background: #f8f9fa; }
        th { padding: 15px; text-align: left; font-weight: 600; color: #666; font-size: 14px; }
        td { padding: 15px; border-top: 1px solid #f0f0f0; font-size: 14px; }
        tbody tr:hover { background: #f8f9fa; }
        .role-badge { padding: 4px 12px; border-radius: 12px; font-size: 12px; margin-right: 5px; }
        .role-admin { background: #fee2e2; color: #dc2626; }
        .role-teacher { background: #dbeafe; color: #2563eb; }
        .role-student { background: #d1fae5; color: #059669; }
        .status-enabled { background: #d1fae5; color: #059669; padding: 4px 12px; border-radius: 12px; font-size: 12px; }
        .status-disabled { background: #fee2e2; color: #dc2626; padding: 4px 12px; border-radius: 12px; font-size: 12px; }
        .btn-small {
            padding: 6px 12px;
            border: none;
            border-radius: 6px;
            cursor: pointer;
            font-size: 12px;
            margin-right: 5px;
        }
        .btn-edit { background: #dbeafe; color: #2563eb; }
        .btn-delete { background: #fee2e2; color: #dc2626; }
        .btn-toggle { background: #fef3c7; color: #d97706; }
        
        /* 模态框 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.5);
            z-index: 2000;
            align-items: center;
            justify-content: center;
        }
        .modal.show { display: flex; }
        .modal-content {
            background: white;
            border-radius: 12px;
            padding: 30px;
            max-width: 500px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
        }
        .modal-header { font-size: 20px; font-weight: 600; margin-bottom: 20px; color: #333; }
        .form-group { margin-bottom: 15px; }
        .form-group label { display: block; margin-bottom: 5px; font-size: 14px; color: #666; }
        .form-group input, .form-group select {
            width: 100%;
            padding: 10px;
            border: 1px solid #e0e0e0;
            border-radius: 8px;
            font-size: 14px;
        }
        .modal-actions {
            display: flex;
            gap: 10px;
            justify-content: flex-end;
            margin-top: 20px;
        }
        .btn-cancel { padding: 10px 20px; background: #f0f0f0; color: #666; border: none; border-radius: 8px; cursor: pointer; }
        .btn-confirm { padding: 10px 20px; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); color: white; border: none; border-radius: 8px; cursor: pointer; }
    </style>
</head>
<body>
    <!-- 顶部导航栏 -->
    <div class="top-nav">
        <a href="/admin/index" class="logo">
            <i class="ri-admin-line"></i>
            <span>管理员控制台</span>
        </a>
        <a href="/perform_logout" class="logout-btn">
            <i class="ri-logout-box-line"></i> 退出登录
        </a>
    </div>

    <!-- 主容器 -->
    <div class="container">
        <div class="page-header">
            <h1 class="page-title">用户管理</h1>
            <button class="btn-primary" onclick="showAddUserModal()">
                <i class="ri-user-add-line"></i> 添加用户
            </button>
        </div>

        <!-- 提示消息 -->
        <div class="alert alert-success" th:if="${success}" th:text="${success}"></div>
        <div class="alert alert-error" th:if="${error}" th:text="${error}"></div>

        <!-- 用户列表 -->
        <div class="users-table-container">
            <div class="table-header">
                <h3>用户列表（共 <span th:text="${users.size()}">0</span> 人）</h3>
            </div>

            <table>
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>用户名</th>
                        <th>姓名</th>
                        <th>邮箱</th>
                        <th>角色</th>
                        <th>状态</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr th:each="user : ${users}">
                        <td th:text="${user.id}">1</td>
                        <td th:text="${user.username}">admin</td>
                        <td th:text="${user.name}">管理员</td>
                        <td th:text="${user.email}">email</td>
                        <td>
                            <th:block th:each="role : ${user.roles}">
                                <span th:text="${role.roleName}" class="role-badge role-admin">角色</span>
                            </th:block>
                        </td>
                        <td>
                            <span th:text="${user.enabled ? '启用' : '禁用'}" 
                                  th:class="${user.enabled ? 'status-enabled' : 'status-disabled'}">
                                启用
                            </span>
                        </td>
                        <td>
                            <button class="btn-small btn-edit" th:attr="data-id=${user.id}, data-username=${user.username}, data-name=${user.name}, data-email=${user.email}, data-enabled=${user.enabled}" onclick="editUser(this)">
                                <i class="ri-edit-line"></i> 编辑
                            </button>
                            <button class="btn-small btn-edit" th:attr="data-id=${user.id}, data-username=${user.username}" onclick="managePermissions(this)">
                                <i class="ri-key-line"></i> 权限
                            </button>
                            <button class="btn-small btn-delete" th:attr="data-id=${user.id}, data-username=${user.username}" onclick="deleteUser(this)">
                                <i class="ri-delete-bin-line"></i> 删除
                            </button>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>

    <!-- 添加用户模态框 -->
    <div id="addUserModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">添加新用户</div>
            <form action="/admin/users/add" method="post">
                <div class="form-group">
                    <label>用户名 *</label>
                    <input type="text" name="username" required>
                </div>
                <div class="form-group">
                    <label>姓名</label>
                    <input type="text" name="name">
                </div>
                <div class="form-group">
                    <label>邮箱</label>
                    <input type="email" name="email">
                </div>
                <div class="form-group">
                    <label>角色 *</label>
                    <select name="roleCode" required>
                        <option value="0">管理员</option>
                        <option value="1">教师</option>
                        <option value="2" selected>学生</option>
                    </select>
                </div>
                <div class="form-group">
                    <label>密码 *</label>
                    <input type="password" name="password" required>
                </div>
                <div class="modal-actions">
                    <button type="button" class="btn-cancel" onclick="closeAddUserModal()">取消</button>
                    <button type="submit" class="btn-confirm">添加</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 编辑用户模态框 -->
    <div id="editUserModal" class="modal">
        <div class="modal-content">
            <div class="modal-header">编辑用户</div>
            <form id="editUserForm" method="post">
                <input type="hidden" id="editUserId">
                <div class="form-group">
                    <label>用户名</label>
                    <input type="text" id="editUsername" readonly style="background: #f0f0f0;">
                </div>
                <div class="form-group">
                    <label>姓名</label>
                    <input type="text" id="editName" name="name">
                </div>
                <div class="form-group">
                    <label>邮箱</label>
                    <input type="email" id="editEmail" name="email">
                </div>
                <div class="form-group">
                    <label><input type="checkbox" id="editEnabled" name="enabled" value="true"> 启用账号</label>
                </div>
                <div class="modal-actions">
                    <button type="button" class="btn-cancel" onclick="closeEditUserModal()">取消</button>
                    <button type="submit" class="btn-confirm">保存</button>
                </div>
            </form>
        </div>
    </div>

    <!-- 权限管理模态框 -->
    <div id="permissionModal" class="modal">
        <div class="modal-content" style="max-width: 800px;">
            <div class="modal-header">管理用户权限：<span id="permUsername"></span></div>
            
            <h4 style="margin: 20px 0 10px; color: #667eea;">角色权限（继承自角色）</h4>
            <div id="rolePermissionsList" style="margin-bottom: 20px;">
                <!-- 角色权限将通过JavaScript动态加载 -->
            </div>
            
            <h4 style="margin: 20px 0 10px; color: #667eea;">直接分配的权限</h4>
            <div id="directPermissionsList" style="margin-bottom: 20px;">
                <!-- 直接权限将通过JavaScript动态加载 -->
            </div>
            
            <h4 style="margin: 20px 0 10px; color: #667eea;">添加新权限</h4>
            <div class="form-group">
                <select id="newPermissionSelect">
                    <option value="">选择要添加的权限</option>
                    <option th:each="perm : ${allPermissions}" th:value="${perm.id}" th:text="${perm.permName + ' (' + perm.permCode + ')'}">权限</option>
                </select>
            </div>
            
            <div class="modal-actions">
                <button type="button" class="btn-cancel" onclick="closePermissionModal()">关闭</button>
                <button type="button" class="btn-confirm" onclick="addPermission()">添加权限</button>
            </div>
        </div>
    </div>

    <script>
        function showAddUserModal() {
            document.getElementById('addUserModal').classList.add('show');
        }
        
        function closeAddUserModal() {
            document.getElementById('addUserModal').classList.remove('show');
        }
        
        function editUser(btn) {
            const id = btn.getAttribute('data-id');
            const username = btn.getAttribute('data-username');
            const name = btn.getAttribute('data-name') || '';
            const email = btn.getAttribute('data-email') || '';
            const enabled = btn.getAttribute('data-enabled') === 'true';
            
            document.getElementById('editUserId').value = id;
            document.getElementById('editUsername').value = username;
            document.getElementById('editName').value = name;
            document.getElementById('editEmail').value = email;
            document.getElementById('editEnabled').checked = enabled;
            document.getElementById('editUserForm').action = '/admin/users/edit/' + id;
            document.getElementById('editUserModal').classList.add('show');
        }
        
        function closeEditUserModal() {
            document.getElementById('editUserModal').classList.remove('show');
        }
        
        function deleteUser(btn) {
            const id = btn.getAttribute('data-id');
            const username = btn.getAttribute('data-username');
            
            if (username === 'admin' || username === 'superadmin' || username === 'manager') {
                alert('不能删除系统管理员账号！');
                return;
            }
            
            if (confirm('确定要删除用户 "' + username + '" 吗？\n\n此操作不可撤销！')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '/admin/users/delete/' + id;
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        // 权限管理
        let currentPermUserId = null;
        
        async function managePermissions(btn) {
            currentPermUserId = btn.getAttribute('data-id');
            const username = btn.getAttribute('data-username');
            
            document.getElementById('permUsername').textContent = username;
            
            // 加载用户权限信息
            await loadUserPermissions(currentPermUserId);
            
            document.getElementById('permissionModal').classList.add('show');
        }
        
        async function loadUserPermissions(userId) {
            try {
                const response = await fetch('/api/user-permissions/' + userId);
                const data = await response.json();
                
                // 显示角色权限
                const rolePermsList = document.getElementById('rolePermissionsList');
                if (data.rolePermissions && data.rolePermissions.length > 0) {
                    rolePermsList.innerHTML = data.rolePermissions.map(perm => 
                        `<span class="role-badge role-student" style="margin: 5px;">
                            ${perm.name} (${perm.code}) - ${perm.source}
                        </span>`
                    ).join('');
                } else {
                    rolePermsList.innerHTML = '<div style="color: #999;">无角色权限</div>';
                }
                
                // 显示直接权限
                const directPermsList = document.getElementById('directPermissionsList');
                if (data.directPermissions && data.directPermissions.length > 0) {
                    directPermsList.innerHTML = data.directPermissions.map(perm => 
                        `<span class="role-badge role-teacher" style="margin: 5px;">
                            ${perm.name} (${perm.code})
                            <i class="ri-close-line" style="cursor: pointer; margin-left: 5px;" 
                               onclick="removePermission(${userId}, ${perm.id}, '${perm.name}')"></i>
                        </span>`
                    ).join('');
                } else {
                    directPermsList.innerHTML = '<div style="color: #999;">暂无直接分配的权限</div>';
                }
            } catch (error) {
                console.error('加载权限信息失败:', error);
                alert('加载权限信息失败，请刷新页面重试');
            }
        }
        
        function addPermission() {
            const permId = document.getElementById('newPermissionSelect').value;
            
            if (!permId) {
                alert('请选择要添加的权限！');
                return;
            }
            
            const form = document.createElement('form');
            form.method = 'POST';
            form.action = '/admin/users/add-permission/' + currentPermUserId;
            
            const input = document.createElement('input');
            input.type = 'hidden';
            input.name = 'permissionId';
            input.value = permId;
            form.appendChild(input);
            
            document.body.appendChild(form);
            form.submit();
        }
        
        function removePermission(userId, permId, permName) {
            if (confirm('确定要移除权限 "' + permName + '" 吗？')) {
                const form = document.createElement('form');
                form.method = 'POST';
                form.action = '/admin/users/remove-permission/' + userId;
                
                const input = document.createElement('input');
                input.type = 'hidden';
                input.name = 'permissionId';
                input.value = permId;
                form.appendChild(input);
                
                document.body.appendChild(form);
                form.submit();
            }
        }
        
        function closePermissionModal() {
            document.getElementById('permissionModal').classList.remove('show');
        }
        
        window.onclick = function(event) {
            if (event.target.classList.contains('modal')) {
                closeAddUserModal();
                closeEditUserModal();
                closePermissionModal();
            }
        }
        
        // 自动隐藏提示
        setTimeout(() => {
            document.querySelectorAll('.alert').forEach(alert => {
                alert.style.display = 'none';
            });
        }, 5000);
    </script>
</body>
</html>
